import { Context } from "koa";
import jwt from "jsonwebtoken";
import response from "../../utils/response"; // 统一返回接口
import db from "../../utils/db"; // 数据库连接
import validate from "../../utils/validate";
import { Rules } from "async-validator";
import LoginService from "../service/LoginService";
import { sign } from "../../utils/auth";

class LoginController {
  /** get请求访问login登录页面 */
  async index(ctx: Context): Promise<any> {
    console.log('get请求登录页面');
    console.log(ctx.request.body);
    response.success(ctx, ['LoginController-get请求登录页面']);
  }

  /** post请求访问login登录页面 */
  async postLogin(ctx: Context) {
    console.log('post请求登录页面');
    console.log(ctx.request.body);
    const rules: Rules = {
      name: [
        {
          type: 'string',
          required: true,
          message: '用户名不可以为空'
        }
      ],
      password: [
        {
          type: 'string',
          required: true,
          message: '密码不可以为空'
        }
      ]
    }
    interface IAdmin {
      name: string
      password: string
    }
    const { data, error } = await validate<IAdmin>(ctx, rules);
    if (error !== null) {
      return response.error(ctx, error);
    }

    //通过用户名查询数据库,获取用户是否存在
    let currentUser = await LoginService.getUserByName(data.name);
    if (currentUser) {
      if (currentUser.pwd === data.password) {
        // 登录成功，生成token
        const token = sign(currentUser);
        //const token = jwt.sign({ name: data.name, password: data.password}, 'secret', { expiresIn: 3600 })
        response.success(ctx, [{
          humanId: currentUser.id,
          humanName: currentUser.account,
          token,
        }]);
      } else {
        response.error(ctx, data.name+'---密码错误');
      }
    }else{
      // 找不到对应的账号
      response.error(ctx, data.name + '---账号不存在');
    }
  }

  async postRegister(ctx: Context) {
    let myaccount = ctx.request.body.account;
    let mypwd = ctx.request.body.pwd;
    let sql = `SELECT * FROM users WHERE account='${myaccount}'`;
    let result: any = await new Promise((resolve, reject) => {
      return db.query(sql, (err: any, data: any) => {
        if (err) throw err;
        if (data.length > 0) {
          resolve(data);
        } else {
          resolve(false);
        }
      })
    })
    if (result) {
      // 能找到对应的账号
      if (result[0].pwd == mypwd) {
        // 账号密码正确，返回token
        ctx.body = {
          token: result[0],
          msg: '登录成功',
          account: myaccount
        };
      } else {
        // 密码错误
        ctx.body = {
          msg: '密码错误',
          account: myaccount
        };
      }
    } else {
      // 找不到对应的账号，直接插入一个
      let result1 = await new Promise((resolve, reject) => {
        // 生成token
        const token = jwt.sign({ myaccount: myaccount, mypwd: mypwd }, 'secret', { expiresIn: 3600 })
        return db.query(`INSERT INTO users (account, pwd, token) values ('${myaccount}', '${mypwd}', '${token}')`, (error: any, datas: any) => {
          if (error) throw error;
          // 已插入数据，返回用户名与token
          let obj = {
            token,
            msg: '登录成功',
            account: myaccount
          }
          resolve(obj)
        })
      })
      if (result1) {
        ctx.body = result1;
      }
    }
  }
}

export default new LoginController